#include "calendar.h"
#include <stdio.h>
#include <time.h>

// 判断闰年
int IsLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 获取某月天数
int GetMonthDays(int year, int month) {
    static const int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if (month == 2 && IsLeapYear(year))
        return 29;
    return days[month-1];
}

// 获取某天是星期几（0-6，0为周日）
int GetWeekday(int year, int month, int day) {
    struct tm t = {0};
    t.tm_year = year - 1900;
    t.tm_mon = month - 1;
    t.tm_mday = day;
    mktime(&t);
    return t.tm_wday;
}

// JDN算法静态函数，适用于公元前4713年11月24日（-4712-01-01）及以后
static long long jdn(int y, int m, int d) {
    if (m <= 2) { y -= 1; m += 12; }
    int A = y / 100;
    int B = 2 - A + A / 4;
    long long jdn = (long long)(365.25 * (y + 4716))
                 + (long long)(30.6001 * (m + 1))
                 + d + B - 1524;
    return jdn;
}

// 计算两个日期之间的天数差（JDN算法）
int DaysBetween(int y1, int m1, int d1, int y2, int m2, int d2) {
    long long jd1 = jdn(y1, m1, d1);
    long long jd2 = jdn(y2, m2, d2);
    return (int)(jd2 - jd1);
}

// 某天加n天后的日期
void AddDays(int year, int month, int day, int n, int *ry, int *rm, int *rd) {
    static const int days_in_month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    int y = year, m = month, d = day + n;
    // 正向或反向调整天数
    while (d > GetMonthDays(y, m)) {
        d -= GetMonthDays(y, m);
        m++;
        if (m > 12) { m = 1; y++; }
    }
    while (d < 1) {
        m--;
        if (m < 1) { m = 12; y--; }
        d += GetMonthDays(y, m);
    }
    *ry = y;
    *rm = m;
    *rd = d;
} 
